import { type FC, useRef } from "react";
import ReactQuill from "react-quill";
import { Space, Button, message, Spin } from "antd";
import useArtEditStore, { updateCurrent, selectContent, setArticleContent, setArticleState, selectIsShowDraft } from "@/store/art-edit-store";
import { Move } from "@/store/art-add-store";

import { useSubmit } from "react-router-dom";
import { useNavSubmitting } from "@/utils/hooks";

import styles from "@/components/article-add/css/art-content.module.less";
import { modules } from "@/components/article-add/art-content";

const EditContent: FC = () => {
  // 选取全局的文章内容
  const value = useArtEditStore(selectContent);
  const submit = useSubmit();
  const submitting = useNavSubmitting("PUT");

  const isShowDraft = useRef(useArtEditStore(selectIsShowDraft));

  // 按钮的点击事件处理函数
  const publish = (state: "草稿" | "已发布") => {
    if (!value) return message.error("请填写文章的内容！");
    setArticleState(state);
    submit(null, { method: "PUT", navigate: false });
  };

  return (
    <div className={styles.artContent}>
      <Spin spinning={submitting} delay={200}>
        <Space direction="vertical" style={{ display: "flex" }}>
          <ReactQuill theme="snow" value={value} onChange={setArticleContent} modules={modules} />

          {/* 按钮区域 */}
          <Space>
            <Button type="primary" onClick={() => updateCurrent(Move.prev)}>
              上一步
            </Button>
            <Button type="primary" onClick={() => publish("草稿")} style={{ display: isShowDraft.current ? "" : "none" }}>
              存为草稿
            </Button>
            <Button type="primary" onClick={() => publish("已发布")}>
              发布
            </Button>
          </Space>
        </Space>
      </Spin>
    </div>
  );
};

export default EditContent;
